package com.hanlink.dsp.bluetooth.ble;

import android.util.Log;

import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.qztech.sdk.utils.ByteUtil;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

public class WriteThread
        extends Thread {
    private boolean canWrite = true;
    private LinkedBlockingQueue<byte[]> mBuffers = new LinkedBlockingQueue();
    private UUID mCharacterUUID;
    private String mMac;
    private UUID mServiceUUID;
    private long mThreadwait = 15L;

    public WriteThread(String paramString, UUID paramUUID1, UUID paramUUID2) {
        this.mMac = paramString;
        this.mServiceUUID = paramUUID1;
        this.mCharacterUUID = paramUUID2;
    }

    public void add(byte[] paramArrayOfByte) {
        this.mBuffers.add(paramArrayOfByte);
    }

    public void clearUploadBuffer() {
        this.mBuffers.clear();
    }

    public int getCount() {
        if (this.mBuffers != null) {
            return this.mBuffers.size();
        }
        return 0;
    }

    public void offerBuffer(byte[] paramArrayOfByte) {
        this.mBuffers.offer(paramArrayOfByte);
    }

    @Override
    public void run() {
        byte[] arrayOfByte = null;
        while (this.canWrite) {
            try {
                arrayOfByte = this.mBuffers.take();
                write(arrayOfByte);
                this.mBuffers.remove(arrayOfByte);
                Thread.sleep(this.mThreadwait);
            } catch (Exception localException) {
                this.canWrite = false;
                localException.printStackTrace();
            }
        }
        Log.d("ble", "stop write");
    }

    public void stopWrite() {
        this.canWrite = false;
        mBuffers.clear();
        if (!isInterrupted()) {
            interrupt();
        }
    }

    public void write(byte[] paramArrayOfByte)
            throws IOException {
        Log.d("Ble", "write :" + ByteUtil.bytesToHexString(paramArrayOfByte));
        ClientManager.getClient().writeNoRsp(this.mMac, this.mServiceUUID, this.mCharacterUUID, paramArrayOfByte, new BleWriteResponse() {
            public void onResponse(int paramAnonymousInt) {
                Log.d("Ble", "write response:" + paramAnonymousInt);
            }
        });
    }
}
